package com.aiton.bamin.bamindaijiadrier.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.refreshview.CustomerFooter;
import com.aiton.administrator.shane_library.shane.refreshview.XRefreshView;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.adapter.MyAppointedBillAdapter;
import com.aiton.bamin.bamindaijiadrier.adapter.MyBillAdapter;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.AppointedBill;
import com.aiton.bamin.bamindaijiadrier.model.Bill;
import com.aiton.bamin.bamindaijiadrier.model.Wallet;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class BillActivity extends ZjbBaseActivity implements View.OnClickListener {

    private RelativeLayout mRela_bill_null;
    private ListView mList_all_bill;
    private ListView mList_search_bill;
    private XRefreshView mCustom_view;
    private TextView mTv_bill_null;
    private Wallet.DatasBean mWallet;
    private MyBillAdapter mMyBillAdapter;
    private int billPageCount = 1;
    private MaterialCalendarView mWidget;
    private Date time = Calendar.getInstance().getTime();
    private static final DateFormat FORMATTER = SimpleDateFormat.getDateInstance();
    private String replace;
    private Bill allBill;
    private List<Bill.ResultsBean> mDatas = new ArrayList<>();
    private List<AppointedBill.DatasBean> mAppointedDatas = new ArrayList<>();

    private int mPages;
    private MyAppointedBillAdapter mMyAppointedBillAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bill);
        init();
    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mWallet = (Wallet.DatasBean) intent.getSerializableExtra(Constant.INTENT_KEY.WALLET);
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void findID() {
        mRela_bill_null = (RelativeLayout) findViewById(R.id.rela_bill_null);
        mList_all_bill = (ListView) findViewById(R.id.list_all_bill);
        mList_search_bill = (ListView) findViewById(R.id.list_search_bill);
        mCustom_view = (XRefreshView) findViewById(R.id.custom_view);
        mTv_bill_null = (TextView) findViewById(R.id.tv_bill_null);
    }

    @Override
    protected void initViews() {
        mMyBillAdapter = new MyBillAdapter(this,mDatas);

        mMyAppointedBillAdapter = new MyAppointedBillAdapter(this,mAppointedDatas);

        mList_all_bill.setAdapter(mMyBillAdapter);
        mList_search_bill.setAdapter(mMyAppointedBillAdapter);

        initRefreshView();
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
        findViewById(R.id.img_search).setOnClickListener(this);

    }
    /**
     * 刚开始进入自动下拉刷新
     */
    private void initRefreshView() {
        mCustom_view = (XRefreshView) findViewById(R.id.custom_view);
        mCustom_view.setPullLoadEnable(true);
        mCustom_view.setPinnedTime(1000);
        mCustom_view.setAutoLoadMore(true);
        mCustom_view.setMoveForHorizontal(true);
        mCustom_view.setAutoLoadMore(false);
        mCustom_view.setCustomFooterView(new CustomerFooter(this));
        mCustom_view.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                mDatas.clear();
                billPageCount = 1;
//                hasUnFinishOrder();
                loadBills();
                mTv_bill_null.setVisibility(View.GONE);
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                Log.e("onLoadMore ", "onLoadMore " + isSlience);
                mCustom_view.stopLoadMore();

                if (allBill.isHasNext()) {
                    loadBills();

                } else {
                    mCustom_view.stopLoadMore();
                    Toast.makeText(BillActivity.this, "没有更多账单了", Toast.LENGTH_SHORT).show();
                }
            }
        });
        /**
         * 根据用户id查询所有订单号
         */
        mCustom_view.startRefresh();
    }

    /**
     * 加载账单内容
     */
    private void loadBills(){
        String url = Constant.Url.DRIVER_NOTECASE_RECORD;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
        params.put("driverId",mWallet.getDriverId() );
        params.put("page", "" + billPageCount);
            asyncHttpClient.post(url,params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    Log.e("BillActivity", "账单: --->>" +s );

                    try {
                        //每查询一次页数要+1
                        billPageCount++;
                        allBill = GsonUtils.parseJSON(s, Bill.class);
                        List<Bill.ResultsBean> results = allBill.getResults();
                        mDatas.addAll(results);
                        mPages = allBill.getPageNo();

                        Log.e("AllOrderActivity", "mDatas: --->>" + mDatas.size());
                        if (mDatas.size() > 0) {
                            mTv_bill_null.setVisibility(View.GONE);

                        } else {
                            mTv_bill_null.setVisibility(View.VISIBLE);
                        }
                        mMyBillAdapter.notifyDataSetChanged();
                        mCustom_view.stopRefresh();
                    }catch (Exception e){
                        Toast.makeText(BillActivity.this, "数据解析出错", Toast.LENGTH_SHORT).show();

                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("AllOrderActivity", "下载订单失败");
                    Toast.makeText(BillActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                    mCustom_view.stopRefresh();
                }
            });
    }
    /**
     * 日历控件
     */
    private class SearchCalendarDialog extends Dialog implements OnDateSelectedListener {
        public SearchCalendarDialog(Context context) {
            super(context);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            View view = getLayoutInflater().inflate(R.layout.dialog_calendar, null);
            setContentView(view);
            TextView mTv_all_bill = (TextView) view.findViewById(R.id.textView_all_order);
            mWidget = (MaterialCalendarView) view.findViewById(R.id.calendarView);

            mWidget.setOnDateChangedListener(this);
            mTv_all_bill.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mList_search_bill.setVisibility(View.GONE);
                    mCustom_view.setVisibility(View.VISIBLE);

                    initRefreshView();
                    dismiss();
                }
            });
            Log.e("SearchCalendarDialog", "onCreate: --->>" + time);
            mWidget.setSelectedDate(time);
        }

        @Override
        public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {

            String format = FORMATTER.format(date.getDate());
            time = date.getDate();
            mWidget.setSelectedDate(time);

            dismiss();
            replace = format.replace("年", "-").replace("月", "-").replace("日", "");
            Log.e("SearchCalendarDialog", "日历: --->>" + replace);
            Toast.makeText(BillActivity.this, format, Toast.LENGTH_SHORT).show();
            loadSearchOrder();
        }
    }

    /**
     * 加载搜索的订单
     */
    private void loadSearchOrder() {
        showLoadingDialog();
        String url = Constant.Url.FIND_OLD_NOTECASE_RECORD_BY_DAY;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("driverId", mWallet.getDriverId());
        params.put("startDate", replace);

        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
                    Log.e("AllOrderActivity", "搜索的订单: --->>" + s);
                    AppointedBill appointedOrder = GsonUtils.parseJSON(s, AppointedBill.class);
                    if (appointedOrder.getStatus() == 0) {
                        List<AppointedBill.DatasBean> appointedOrderDatas = appointedOrder.getDatas();

                        mAppointedDatas.clear();
                        mAppointedDatas.addAll(appointedOrderDatas);
                        mMyAppointedBillAdapter.notifyDataSetChanged();
                        mCustom_view.setVisibility(View.GONE);
                        mList_search_bill.setVisibility(View.VISIBLE);
                        mTv_bill_null.setVisibility(View.GONE);
                    } else {
                        mCustom_view.setVisibility(View.GONE);
                        mList_search_bill.setVisibility(View.GONE);
                        mTv_bill_null.setVisibility(View.VISIBLE);
                    }
                    cancelLoadingDialog();
                } catch (Exception e) {
                    Toast.makeText(BillActivity.this, "文件解析错误", Toast.LENGTH_SHORT).show();
                    mCustom_view.setVisibility(View.GONE);
                    mList_search_bill.setVisibility(View.GONE);
                    mTv_bill_null.setVisibility(View.VISIBLE);
                    cancelLoadingDialog();
                }
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(BillActivity.this, "加载订单失败，服务器出错", Toast.LENGTH_SHORT).show();
                mCustom_view.setVisibility(View.GONE);
                mList_search_bill.setVisibility(View.GONE);
                cancelLoadingDialog();

            }
        });
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.img_search://搜索订单
                new SearchCalendarDialog(this).show();
                break;
        }
    }
}
